package com.wangzifan.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wangzifan.entity.Result;
import com.wangzifan.properties.JwtProperties;
import com.wangzifan.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    private final JwtProperties jwtProperties;

    public LoginCheckInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空，返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //不在controller当中，添加依赖手动转JSON
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        try {
            JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), jwt);
        } catch (Exception e) {
            log.info("令牌解析失败，返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            //不在controller当中，添加依赖手动转JSON
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        //令牌合法，放行
        return true;
    }
}
